package com.chenjt.customizePage.smsCode;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 注释：构造已认证的SmsCodeAuthenticationToken
 *
 * 短信验证码的验证在SmsCodeAuthenticationFilter之前做验证（SmsCodeValidateFilter），不要放在SmsCodeAuthenticationFilter和provider中，也是为了代码能复用
 *
 * @author chenjt
 * @date 2025/2/5 9:19
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {


    private UserDetailsService userDetailsService;

    /**
     * 获取用户信息，重新组装已认证的AuthenticationToken
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken)authentication;

        UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());

        if(user == null){
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }

        // 该构造方法中有super.setAuthenticated(true); 设置该用户名认证通过
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user, user.getAuthorities());

        // 将未认证的用户信息设置到已认证的token中
        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    /**
     * AuthenticationManager根据supports去找哪个provider去验证传进来的token
     *
     * 当传进来的token是SmsCodeAuthenticationToken.class这个类型的时候，
     * AuthenticationManager就会挑SmsCodeAuthenticationProvider这个provider调用authenticate()去做处理
     * @param authentication
     * @return
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailsService getUserDetailsService(){
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

}
